package com.jerry.boot.business.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jerry.boot.business.user.pojo.UserInfo;
import com.jerry.boot.business.user.pojo.UserPageReq;
import com.jerry.boot.core.mvc.JsonResult;
import com.jerry.boot.core.mvc.PageBase;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User getUserByUsername(String username) {
        return this.getOne(Wrappers.lambdaQuery(User.class)
                .eq((SFunction<User, String>) User::getUsername, username)
        );
    }

    @Override
    public void updateUserLastLoginTime(String username) {
        User user = this.getUserByUsername(username);
        user.setLastLoginTime(new Date());
        this.updateById(user);
    }

    @Override
    public PageBase<UserInfo> queryPage(UserPageReq userPageReq) {
        IPage<User> reqPage = new Page<>(userPageReq.getPage(), userPageReq.getLimit());
        IPage<User> resPage = this.page(reqPage, Wrappers.lambdaQuery(User.class)
                .like(StrUtil.isNotBlank(userPageReq.getUsername()), (SFunction<User, String>) User::getUsername, userPageReq.getUsername())
                .like(StrUtil.isNotBlank(userPageReq.getEmail()), (SFunction<User, String>) User::getEmail, userPageReq.getEmail())
                .like(StrUtil.isNotBlank(userPageReq.getMobile()), (SFunction<User, String>) User::getMobile, userPageReq.getMobile())
                .like(userPageReq.getGender() != null, (SFunction<User, Integer>) User::getGender, userPageReq.getGender())
        );
        PageBase<UserInfo> result = new PageBase<>();
        result.setCode(0);
        result.setCount(resPage.getTotal());
        result.setData(resPage.getRecords().stream().map(x -> {
            UserInfo userInfo = new UserInfo();
            BeanUtil.copyProperties(x, userInfo);
            return userInfo;
        }).collect(Collectors.toList()));
        return result;
    }

    @Override
    public JsonResult update(UserInfo userInfo) {
        User user = new User();
        BeanUtil.copyProperties(userInfo, user);
        this.updateById(user);
        return JsonResult.ok();
    }
}
